<?php
/**
 * 商品模型
 */
namespace app\index\model;
use think\Model;
class Goods extends Model{

	/**
	 * 获取某个分类下的过滤商品信息
	 * @param  $cid   分类id
	 * @return array  返回整理好的商品信息
	 */
    public function getFilterGoods( $cid ){
        
    	// 获取该分类或其子分类或扩展分类为此分类的商品
    	$catGoodsData = $this->getCatsGoods( $cid );
    	$catGoods = $catGoodsData['goods'];
    	$gids = $catGoodsData['gids'];
    	$attrIdsList = $catGoodsData['attrIdsList'];
    	
    	// 存储查询条件信息
    	$brands = [];
    	$priceRange = [];
    	$attr_filter = [];
    	
    	// 如果存在商品
    	if( array_filter($catGoods) ) {

    		// 获取url参数
	    	$url = request()->param();
            //q($url);

	    	// 处理商品价格
	    	$info = $this->getPrice( $catGoods, $url );
	    	$catGoods = $info["goods"];
	    	$sortBtnLinks = $info["sortBtnLinks"];

	    	// 获取商品品牌
	    	$brands = $this->getBrand( $info["bids"], $url );

	    	// 获取价格区间
	    	$priceRange = $this->getPriceRange($info["minPrice"]+0,$info["maxPrice"]+0,$cid,$catGoods,$url);
	    	// q($priceRange);
	    	// 获取过滤属性
	    	$data = $this->getFilterAttrs( $catGoods, $url, $cid, $gids, $attrIdsList );
	    	$attrs = $data["attrs"];
	    	$catGoods = $data["goods"];

	    	// 筛选商品
	    	$goods = $this->getGoodsByFilter($catGoods, count($attrs) );
    		
    	}else{

    		$goods = [];
    		$attrs = [];
    	}
    	
    	return ["goods"=>$goods,"brands"=>$brands,"priceRange"=>$priceRange,'attrs'=>$attrs,'sortBtnLinks'=>$sortBtnLinks];

    }

    /**
	 * 获取某个分类或其子分类或扩展分类为此分类的商品
	 * @param  $cid   分类id
	 * @return array  返回整理好的商品信息
	 */
    private function getCatsGoods( $cid ){
       
    	// 获取子集分类及其本身id数组
        $where = ''; 
        if( $cid ) {

        	$catsAll = db('category')->field('cid,parent_id')->select();
        	$allIds = $this->getSonIds( $catsAll, $cid );
        	$allIds[] = $cid;
        	
        	// 拼凑获取分类下商品条件
        	$where = $allIds ? 'AND ( g.cid IN( '.implode(',', $allIds).' ) OR gc.cid IN ('.implode(',', $allIds).') )' : '';

        }

    	// 拼凑品牌过滤条件
    	$brand = input('brand')+0;
    	$brandWhere = '';
    	if( $brand ){

    		$brandWhere = ' AND g.bid = '.$brand;

    	}

    	// 拼凑价格过滤条件
    	$range = array_map('intval', explode('-', input('range')));
    	$rangeWhere = '';
    	if( $range && count($range) == 2 ){
    		
    		$rangeWhere = ' AND ( (g.shop_price >= '.$range[0].' AND g.shop_price <= '.$range[1].') OR ( promote_start_time <= '.time().' AND promote_end_time >= '.time().' AND promote_price >= '.$range[0].' AND promote_price >= '.$range[1].'  ) ) ';

    	}
    	
    	// 拼凑属性过滤条件
		$filter = explode('_', input('filter') );
		$isFilter = array_filter($filter);
		$filterWhere = '';
    	if( $isFilter ){

    		$filter = array_filter($filter);

    		$filterWhere = 'AND ( ga.attr_value = "'.reset($filter).'"';

    		foreach ($filter as $k => $v) {

    			if($k>0) {

    				$filterWhere .= ' OR ga.attr_value = "'.$v.'"';

    			}
    		}
    		$filterWhere .= ' )';
    		
    		

    	}

    	// 上架时间排序
    	$order = '';
    	if( input('ob') == 'time' ) {

    		$order = 'create_time desc';

    	}

        // sphinx关键词搜索
        $keywordWhere = '';
        if( input("keyword") ) {

            // 引入api
            include "../extend/sphinxapi.php";

            // 连接sphinx服务
            $sphinx = new \SphinxClient();
            $sphinx->setServer('localhost',9312);

            // 获取关键词
            $keyword = input("keyword");

            // 获取搜索信息
            $data = $sphinx->query($keyword);

            // 获取搜索id
            $gids = implode( ',', array_keys($data['matches']) ); 

            // 拼凑关键词过滤条件
            $keywordWhere = ' AND g.gid in('.$gids.')';

        }
        

    	// 获取分类下的商品
    	$field = 'distinct g.gid,goods_name,static_url,shop_price,is_promote,promote_price,promote_start_time,promote_end_time,create_time,pic_small,bid';

    	$goods = $this->alias('g')->field( $field )->join('jd_goods_category gc','g.gid = gc.gid','LEFT')->join('jd_goods_attrs ga','g.gid = ga.gid','LEFT')->where( "`is_on_sale` = 1 AND `is_delete` = 0 $keywordWhere $brandWhere $rangeWhere $filterWhere $where " )->order($order)->select()->toArray();

    	$gids = [];
    	$attrIdsList = [];

    	foreach ($goods as $v) {
			$gids[] = $v['gid'];
		}

		$product = db('product')->field("gid,attr_list,attr_value_list")->where(['gid'=>['in',$gids],'product_sku'=>['gt',0]])->select();


    	if( $isFilter && $goods ){

    		$gids = [];
    		//$attrValueList = [];
    		
    		foreach ( $product as $v ) {
    			
    			$attrValues = explode(',', $v['attr_value_list']);
    			$attrIds = explode(',', $v['attr_list']);
    			
    			if( !array_diff($filter, $attrValues) ) {

    				$gids[] = $v['gid'];
    				
    				// if( isset($attrValueList[ $v['gid'] ]) ) {

    				// 	$attrValueList[ $v['gid'] ] = array_merge( $attrValueList[ $v['gid'] ], $attrValues);

    				// }else {

    				// 	$attrValueList[ $v['gid'] ] = $attrValues;

    				// }
    				
    				// 属性值id
    				$attrIdsList = array_merge( $attrIdsList, $attrIds);
    				
    			}

    		}
    		
    		$gids = array_unique($gids);

    		$data = [];
    		foreach ($goods as $v) {
    			
    			if(  in_array( $v['gid'], $gids) ) {


    				// 为后面获取商品属性值列表做准备
    				// if( isset($attrValueList[ $v['gid'] ]) ) {
    					
    				// 	$v['attr_value_list'] = array_unique( $attrValueList[ $v['gid'] ] );

    				// }else{

    				// 	$v['attr_value_list'] = [];

    				// }


    				$data[] = $v;

    			}

    		}

    		$goods = $data;

    	}else{

    		foreach ( $product as $v ) {
    			
    			//$attrValues = explode(',', $v['attr_value_list']);
    			$attrIds = explode(',', $v['attr_list']);
    			
    			// 属性值id
    			$attrIdsList = array_merge( $attrIdsList, $attrIds);
    				
    			
    		}
    	}
    	
    	$attrIdsList = array_unique($attrIdsList);

    	// 获取销量
    	$sales = db('order_goods og')->join('order o','og.rid = o.rid','LEFT')->field(' og.gid, count("og.rid") as num')->where(['gid'=>['in',$gids],'pay_status'=>2])->group('og.gid')->select();

    	// 获取评论数
    	$comments = db('comment')->field('gid,count(*) as num')->where('gid','in',$gids)->group('gid')->select();
    	// q($goods);
    	foreach ($goods as $k => $v) {

    		// 处理销量
    		foreach ($sales as $v1) {
    			
	    		if( $v['gid'] == $v1['gid'] ) {

	    			$goods[$k]['sale'] = $v1['num'];
	    			$saleSort[] = $v1['num'];

	    		}

    		}

    		if( !isset($goods[$k]['sale']) ) {

    			$goods[$k]['sale'] = 0;
    			$saleSort[] = 0;

    		}

    		// 处理评论
    		foreach ($comments as $v1) {
    			
	    		if( $v['gid'] == $v1['gid'] ) {

	    			$goods[$k]['comment'] = $v1['num'];
	    			$commentSort[] = $v1['num'];

	    		}

    		}

    		if( !isset($goods[$k]['comment']) ) {

    			$goods[$k]['comments'] = 0;
    			$commentSort[] = 0;

    		}

    	}

    	// 按照销量排序
    	if( !input('ob') || input('ob') == 'sale' ){

    		array_multisort($saleSort,SORT_DESC,$goods);

    	}

    	// 按照评论排序
    	if( input('ob') == 'comment' ){

    		array_multisort($commentSort,SORT_DESC,$goods);

    	}


   //  	echo $this->getLastSql();
		 
    	return ['goods'=>$goods,'gids'=>$gids,'attrIdsList'=>$attrIdsList];
    }

    /**
     * 处理商品价格、获取品牌id、价格的最大最小值
     * @param  array  $goods 商品信息
     * @param  array  $url   url参数数组
     * @return array         返回整理好的数组
     */
    public function getPrice( $goods, $url ){

    	// 储存商品品牌id
    	$bids = [];

    	// 储存商品价格的最大最小值
    	$maxPrice = 0;
    	$minPrice = 0;
    	// q($goods);
    	// 循环商品
    	foreach ( $goods as $k => $good ) {
    		
    		// 处理价格
            if($good["is_promote"]== 1 && $good["promote_start_time"] < time() && $good["promote_end_time"] > time() ){ 

               $price = $good["promote_price"];

            }else if( session('level') ){ 
                
                $mprice = db("member_price")->where(["gid" => $good["gid"],"lid" => session('level')])->value("member_price");

                if( $mprice >0  ){ // 会员价格大于0就按照会员价格

                   $price = $mprice; 

                }else if( $mprice == 0  ){ // 会员价格等于0就按照折扣率算

                    $level = config("member.level");
                    $rate = $level[session('level')][2]/100;
                    $price = number_format( round( $good['shop_price'] * $rate ), 2,'.',''); 

                }else{ //否则就按照本店家
                    
                   $price = $good['shop_price'];

                } 

            }else{ //否则就按照本店家

               $price = $good['shop_price'];

            } 

            // 用整理好的价格替换本店价
            $goods[$k]['shop_price'] = $price;

            // 将品牌id放入数组
    		$bids[] = $good["bid"];

    		// 获取价格的最大最小值
    		if( !$k ) {

    			$maxPrice = $price;
    			$minPrice = $price;

    		}else {

	    		if( $price > $maxPrice ){

	    			$maxPrice = $price;

	    		}else if( $price < $minPrice ){

	    			$minPrice = $price;

	    		}

    		}

    		// 
    		$priceSort[] = $good["shop_price"]+0;
    		
    	}
    	
    	// 品牌id去重
    	$bids = array_unique($bids);

    	// 拼凑排序按钮连接
    	unset($url['ow']);
    	$sortBtnLinks['sale'] = url('goods/category', array_merge($url,['ob'=>'sale']) ).'#search';
    	$sortBtnLinks['price'] = url('goods/category', array_merge($url,['ob'=>'price','ow'=>'asc']) ).'#search';
    	$sortBtnLinks['comment'] = url('goods/category', array_merge($url,['ob'=>'comment']) ).'#search';
    	$sortBtnLinks['time'] = url('goods/category', array_merge($url,['ob'=>'time']) ).'#search';

    	// 按照价格排序
    	if( input('ob') == 'price' ){

    		if( input('ow') == 'asc'){

    			$way = SORT_ASC;

    			$sortBtnLinks['price'] = url('goods/category', array_merge($url,['ob'=>'price','ow'=>'desc']) ).'#search';

    		}else{

    			$way = SORT_DESC;

    		}

    		array_multisort($priceSort,$way,$goods);

    	}
    	
    	// 整理返回信息
    	return ['goods'=>$goods,'bids'=>$bids,'minPrice'=>$minPrice,'maxPrice'=>$maxPrice,'sortBtnLinks'=>$sortBtnLinks];

    }

    /**
     * 获取商品品牌
     * @param  array  $bids  品牌id数组
     * @param  array  $url   url参数数组
     * @return array         返回品牌信息
     */
    public function getBrand( $bids ,$url ){

    	// 保存当前url选中的品牌id
    	$cur =  isset( $url['brand'] ) ? $url['brand']+0 : 0;

    	// 将品牌id变量从参数数组中移除
    	unset($url['brand']);
    	
    	// 初始品牌信息数组
    	$brands = [
    		0 => [
    			'bid' => 0,
    			'brand_name' => '不限',
    			'brand_name_en' => '',
    			'sort' => 0,
    			'url' => url('goods/category',$url).'#search',
    			'cur' => 0
    		]
    	];

    	// 获取商品品牌
    	$data = db('brand')->field( 'bid,brand_name,brand_name_en,sort' )->where( ['bid'=>["in",$bids],'brand_status'=>1] )->order('sort')->select();

    	// 拼凑url信息
    	$curFlag = true;
    	foreach ($data as $k => $v) {
    		
    		$url['brand'] = $v['bid'];
    		$v['url'] = url('goods/category',$url).'#search';

    		// 检测是否是当前url中的选中项
			if( $cur === $v['bid'] ){

				$v['cur'] = 1;
				$curFlag = false;

			}else{

				$v['cur'] = 0;

			}

			$brands[$k+1] = $v;

    	}

    	// 如果全部检测完毕，仍然没有符合url中的选中值，就让第一个为默认选择
    	if( $curFlag ){

			$brands[0]['cur'] = 1;

		}
    	// q($brands);
    	return $brands;
    }

    /**
     * 获取价格区间
     * @param  intval $minPrice 最小价格
     * @param  intval $maxPrice 最大价格
     * @param  intval $cid      分类id
     * @param  array  $goods    商品信息
     * @param  array  $goods    url参数
     * @return array            返回一个价格区间数组
     */
    public function getPriceRange( $minPrice, $maxPrice, $cid, $goods, $url ){

    	// 保存当前url选中的价格区间
    	$cur =  isset( $url['range'] ) ? $url['range'] : 0;
    	
    	// 将价格区间变量从参数数组中移除
    	unset($url['range']);
    	
    	// 初始化价格区间数组
    	$priceRange[] = [

			'range_name' => '不限',
			'url' => url('goods/category',$url).'#search',
			'cur' => 0
    		
    	];

    	// 如果最大值等于最小值，说明只有一件商品
    	if( $minPrice == $maxPrice ){

    		$endPrice = $goods[0]['shop_price']+0;

    		// 计算取整所要除的数字
			$chu = str_pad('1',strlen($endPrice)-1,'0',STR_PAD_RIGHT);
			
			// 结束值取整
			$endPrice = ceil( $endPrice/$chu ) * $chu -1;

			//
			$range = explode('-', input('range') );
			
			if( count( $range ) != 2 ){

				$priceRange[0]['cur'] = 1;
				$firstCur = 0;

			}else{

				$firstCur = 1;

			}

			$url['range'] = '0'.'-'.$endPrice;

    		$priceRange[] = [
	    		
    			'range_name' => '0-'.$endPrice,
    			'url' => url('goods/category',$url).'#search',
    			'cur' => $firstCur
	    		
    		];

    		
    		if( count( $range ) == 2 ){

    			$priceRange[1]['range_name'] = $url['range'] = input('range');
    			$priceRange[1]['url'] = url('goods/category',$url).'#search';

    		}

    	}else{

    		if( input('range') ){

    			// 拼凑区间信息
    			$priceRange[1]['range_name'] = $url['range'] = input('range');
    			$priceRange[1]['url'] = url('goods/category',$url).'#search';
    			
    			// 检测是否是当前url中的选中项
    			$priceRange[1]['cur'] = 1;

    		}else{

		    	// 获取分类的区间段数
		    	$num = db('category')->where('cid',$cid)->value('price_num');
                $num = $num ? $num : 7;

		    	// 计算每个区间的价格差值
		    	$cha = ceil( ($maxPrice-$minPrice)/$num );

		    	// 拼凑区间
		    	$startPrice = 0;// 初始值
		    	$endPrice = 0;// 结束值
		    	$newEndPrice = 0;// 当区间内不存在商品时，用其保存当前结束值
		    	$flag = true;// 当区间内是否存在商品标识
		    	$curFlag = true;// 是否为当前url参数选中项标识
		    	for($i = 0; $i < $num; $i++ ){

		    		// 计算结束值
		    		if( $flag ){

		    			// 如果是第一次进入
		    			if( $i ==0 ){
		    				
		    				// 要加上最小值
		    				$endPrice = $startPrice+$minPrice+$cha;

		    			}else{

		    				$endPrice = $startPrice+$cha;

		    			}


		    		}else{
		    			
		    			// 如果上次区间内没有商品，那么就不使用$startPrice计算结束值，而是使用$newEndPrice
		    			$endPrice = $newEndPrice+$cha;

		    		}
		    		
		    		// 计算取整所要除的数字
					$chu = str_pad('1',strlen($endPrice)-1,'0',STR_PAD_RIGHT);
					
					// 结束值取整
					$endPrice = ceil( $endPrice/$chu ) * $chu -1;

					// 判断区间下是否存在商品
					$flag = false;
					foreach ($goods as $v) {

						if( $v['shop_price'] >= $startPrice && $v['shop_price'] <= $endPrice ) {
							
							// 存在商品就将其变成true
							$flag = true;
							break;
						}
						
					}

					// 如果该区间下有商品
					if( $flag ){

						// 拼凑区间信息
		    			$priceRange[$i+1]['range_name'] = $url['range'] = $startPrice.'-'.$endPrice;
		    			$priceRange[$i+1]['url'] = url('goods/category',$url).'#search';
		    			// q($url['range']);
		    			// q($cur);
		    			// 检测是否是当前url中的选中项
		    			if( $cur === $url['range'] ){

		    				$priceRange[$i+1]['cur'] = 1;
		    				$curFlag = false;

		    			}else{

		    				$priceRange[$i+1]['cur'] = 0;

		    			}

		    			// 改变初始值
		    			$startPrice = $endPrice+1;

					}else{

						// 改变$newEndPrice，但不改变$startPrice初始值
		    			$newEndPrice = $endPrice+1;

					}

		    	}

		    	// 如果全部检测完毕，仍然没有符合url中的选中值，就让第一个为默认选择
		    	if( $curFlag ){

					$priceRange[0]['cur'] = 1;

				}
			}

    	}
    	//q($priceRange);

    	return $priceRange;

    }

    /**
     * 获取过滤属性
     * @param  array   $goods         商品信息
     * @param  array   $url           url参数数组
     * @param  intval  $cid           分类id
     * @param  array   $gids          商品id
     * @param  array   $attrIdsList   商品属性值id列表
     * @return array                  返回属性信息数组
     */
    public function getFilterAttrs( $goods , $url, $cid, $gids, $attrIdsList ){

    	// 获取分类过滤属性
    	$filterList = db('category')->where('cid',$cid)->value('filter');
    	
    	// 如果自定义了分类过滤属性
    	if( $filterList ){

    		// 将过滤属性字符串变成数组
    		$filterList = explode(',', $filterList);

    		// 添加where条件
    		$where['ga.aid'] = ['in',$filterList];


    	}

    	// 添加where条件
    	$where['ga.gid'] = ['in',$gids];
    	$where['a.attr_type'] = 1;

    	if( $attrIdsList ){

    		$where['ga.id'] = ['in',$attrIdsList];

    	}
    	// q($where);
    	// 获取商品属性
	    $data = db('goods_attrs as ga')->field('ga.id,ga.aid,ga.gid,a.attr_name,ga.attr_value,ga.sort,a.sort')->join('jd_attrs a','ga.aid = a.aid','LEFT')->where( $where )->order('a.sort,ga.sort asc')->select();
	    
	    // 整理属性信息
	    $attrs = [];
    	if( $data ){

    		if( isset( $url['filter'] ) ){

		    	// 将过滤属性id字符串变成数组，并将每一项变成整数
		    	$filter = array_filter( explode('_', $url['filter']) );
		    	 // q($filter);

			}
			// q($goods);
    		// 获取商品属性值列表
	  //   	foreach ($goods as $k => $v) {

	  //   		foreach ($data as $v1) {
	    			
		 //    		if( $v['gid'] == $v1['gid'] ){

		 //    			$goods[$k]['attr_value_list'][] = $v1['attr_value'];
		    			
		 //    		}

			    	
	  //   		}
	    		
	  //   		if( array_diff($filter, $goods[$k]['attr_value_list']) ) {
	  //   			unset($goods[$k]);
	  //   		}
	    		
			// }
			
			// die;

    		//q($goods);
			
    		// 循环所有属性信息
		    foreach ($data as $v) {
		    	
		    	// 检测$attrs数组中是否添加过该属性
		    	if( isset( $attrs[$v['aid']] ) ) {
		    		
		    		// 检测$attr数组中该属性是否添加过这个值
		    		if( !in_array($v['attr_value'], $attrs[$v['aid']]['attr_value'])  ){

		    			// 将值直接加入到该属性的值内
		    			$attrs[$v['aid']]['attr_value'][$v['id']] = $v['attr_value'];

		    		}

		    	}else {

		    		// $attrs数组中还未添加该属性就添加
		    		$attrs[$v['aid']]['attr_name'] =$v['attr_name'];
		    		$attrs[$v['aid']]['attr_value'][0] = '不限';
		    		$attrs[$v['aid']]['attr_value'][$v['id']] =$v['attr_value'];
		    	}

		    	// 获取商品属性值列表
		    	/*foreach ($goods as $k1 => $v1) {


		    		if( $v['gid'] == $v1['gid'] ){

		    			$goods[$k1]['attr_value_list'][] = $v['attr_value'];
		    			
		    		}

		    	}*/

		    }

		   
		   
		    // 保存当前url选中的过滤属性id
		    if( isset( $url['filter'] ) ){

		    	// 将过滤属性id字符串变成数组，并将每一项变成整数
		    	$filter = explode('_', $url['filter']);
		    	
		    	// 将品牌id变量从参数数组中移除
	    		unset($url['filter']);
	    		
	    		// 如果url中传递的属性个数与实际属性个数不同
		    	if( !array_filter($filter)  ){

		    		// 将$filter清空
		    		$filter =[];

		    		// 设置默认值
		    		for( $i = 0; $i < count($attrs); $i++ ){

			    		$filter[] = '0';

			    	}

		    	}

		    }else{

		    	// 如果url中没有传递filter参数，就设置为默认值
		    	for( $i = 0; $i < count($attrs); $i++ ){

		    		// 设置默认值
		    		$filter[] = '0';

		    	}

		    }
	    	
    	}
    	
    	// 处理属性当前选择状态和url
    	$index = 0;
    	foreach ($attrs as $k => $v) {
    		
    		// 将默认过滤属性数组赋值给$now_filter，保证$filter不会被改变
    		$now_filter = $filter;

    		// 循环每一个属性的值
    		foreach ($v['attr_value'] as $k1 => $v1) {

    			// 将当前url默认属性的id变成当前的值
    			$now_filter[$index] = $v1;// == '不限' ? '0' : $v1

    			// 将该属性的当前值字段变成一个空数组，为了后面加内容
    			$attrs[$k]['attr_value'][$k1] = [];
    			
    			// 检测是否是当前url中的选中项
    			$cur = $filter[$index] == '0' ? '不限' : $filter[$index]; 
				if( $v1 == $cur ){

					// 如果当前属性id与url中选择id一样，就让cur为1
					$attrs[$k]['attr_value'][$k1]['cur'] = 1;

				}else{

					// 不相等cur就为0
					$attrs[$k]['attr_value'][$k1]['cur'] = 0;

				}

				// 将字符串"不限"替换成0
				foreach ($now_filter as $k2 => $v2) {
					// q($v2);
					if($v2 == '不限') {

						$now_filter[$k2] = '0';

					}

				}
    			
    			// 如果$now_filter内的值均为0，证明选择的是不限，这样url就不必传递filter参数
    			if( array_filter($now_filter) ){
    				
    				// 为url添加filter参数
    				$url['filter'] = implode('_', $now_filter);
    				// q($now_filter,false);

    			}
    			
    			// 为当前的属性值添加url和值
    			$attrs[$k]['attr_value'][$k1]['url'] = url('goods/category',$url).'#search';
    			$attrs[$k]['attr_value'][$k1]['value'] = $v1;

    			unset($url['filter']);
    			// q($attrs[$k]['attr_value'][$k1]['url'],false);
    			
    		}
			//q($attrs);
    		// 索引自增1
    		$index++;
    		
    	}
	   // q($attrs);
	    // 返回属性
	    return ['attrs'=>$attrs,'goods'=>$goods];

    }

    /*
     * 根据过滤条件选择商品
     * @param  [type] $goods     [description]
     * @param  [type] $attrsNum  [description]
     * @return [type]            [description]
    */
     
    public function getGoodsByFilter( $goods, $attrsNum ){
    	
    	$brand = input("brand")+0;
    	$range = explode('-', input("range") );
    	
    	if( $range && count($range) == 2  ){

			array_map('intval', $range);

			$min = $range[0];
			$max = $range[1];
    		

    	}else{

    		$range = [];

    	}

    	// 将过滤属性id字符串变成数组，并将每一项变成整数
		$filter = explode('_', input('filter') );

    	if( !$brand && !$range && !( $attrsNum && array_filter($filter) && count($filter) == $attrsNum) ){
    		return $goods;
    	}
    	

    	$data = [];

    	foreach ($goods as $v) {

    		if( $brand ) {

	    		if( $v['bid'] == $brand ) {

	    			$data[] = $v;

	    		}

    		}else {

    			$data = $goods;

    		}
    		
    	}

    	if($data && isset($min) ){

    		//$info = [];

	    	foreach ($data as $k=>$v) {

	    		if( !( $v['shop_price'] >= $min && $v['shop_price'] <= $max ) ) {

	    			//$info[] = $v;
	    			unset($data[$k]);

	    		}

	    	}

    	}

		//q($data);
    	// if( $data ){

    	// 	$filter = array_filter($filter);
    		
    	// 	foreach ($data as $k => $v) {
    	// 		//q(array_diff($filter,$v['attr_value_list']));
    	// 		if( array_diff($filter,$v['attr_value_list']) ) {

	    // 			unset($data[$k]);

	    // 		}

    	// 	}

    	// }
    	return $data;
    }

    /**
     * 获取子集id
     * @param  array  $data 包含id属性的数组
     * @param  int    $pid  父级id
     * @return array        返回一个包含所有子集id的一维数组
     */
    public function getSonIds( $data, $pid = 0 ){
    	
    	$arr = [];

    	foreach ($data as $v) {

    		if( $v['parent_id'] == $pid ) {

    			$arr[] = $v['cid']+0;

    			$arr = array_merge($arr, $this->getSonIds( $data, $v['cid'] ) );

    		}
    		
    	}

    	return $arr;

    }

    /**
     * 获取相关分类
     * @param  [type] $cid [description]
     * @return [type]      [description]
     */
    public function getConnectCats( $cid ){

        $catModel = db('category');
        $catIds = $catModel->where('parent_id',$cid)->column('cid');

        if( $catIds ){

            $catIds[] = $cid;

        }else{

            $cid = $catModel->where('cid',$cid)->value('parent_id');
            $catIds = $catModel->where('parent_id',$cid)->column('cid');
            $catIds[] = $cid;

        }

        $allCats = $catModel->field('cid,parent_id,cat_name')->where([ 'parent_id'=>['in',$catIds] ])->whereor('cid',$cid)->select();

        $pid = 0;

        foreach ($allCats as $v) {
             
             if($v['cid'] == $cid){

                $pid = $v['parent_id'];
                break;

             }

        }

        $allCats = $this->getTreeCats( $allCats, $pid );
        $flag = false;
        foreach ($allCats[0]['child'] as $k => $v) {

            if( $v['child'] ) {
                $flag = true;
                break;
            }
            
        }
        $allCats[0]['flag'] = $flag;

        return $allCats;
    }

    /**
     * [getConnectCats description]
     * @param  [type] $cats [description]
     * @param  [type] $pid  [description]
     * @return [type]       [description]
     */
    private function getTreeCats( $cats, $pid ){

        $arr = [];

        foreach ( $cats as $v ) {
            
            if( $v['parent_id'] == $pid ) {

                $v['child'] = $this->getTreeCats( $cats, $v['cid'] );

                $arr[] = $v;

            }

        }

        return $arr;

    }

    /**
     * 获取同类品牌
     * @param  array $gids 商品id
     * @return [type]       [description]
     */
    public function getLikeBrands( $gids ){

        $bids = $this->where('gid','in',$gids)->column('bid');
        $bids = array_unique($bids);
        $brands = db('brand')->field('bid,brand_name')->where('bid','in',$bids)->select();
        return $brands; 

    }

    /**
     * 获取面包屑导航
     * @param  [type] $cats [description]
     * @param  [type] $cid [description]
     * @return [type]      [description]
     */
    public function getNav( $cats, $cid ){
        
        $arr = [];

        foreach ($cats as $v) {
           
           if( $v['cid'] == $cid ) {

                $arr[] = $v;
                $arr = array_merge($arr, $this->getNav( $cats, $v['parent_id'] ) );

           }

        }

        return $arr;

    }

    /**
     * 添加最近浏览商品
     * @param [type] $gid [description]
     */
    public function addRecentviewedGoods( $gid ){

        // 检测用户是否登录，登录就加入数据库，没有就加入cookie中
        // if( session('mid') ){



        // }else{

            // 检测cookie中是否已经设置过最近浏览数据
            if( cookie('recentViews') ){

                // 将cookie中数据反序列化
                $gidArr =  unserialize( cookie('recentViews') );

                // 将原有数据的索引下标加1
                foreach ($gidArr as $k => $v) {
                    $gidArr[$k+1] = $v;
                }

                // 将最新的gid放到开头，因为array_unshift会将原先的索引为0的覆盖，所以上面才做了将索引加1的操作
                array_unshift($gidArr,$gid);

                // 去重，会保留前面出现的值，符合我们的业务
                $gidArr = array_unique($gidArr);

                // 只要前五个
                $gidArr = array_slice($gidArr, 0, 8);
    

            }else{

                // 没有设置过最近浏览数据，就将当前gid放入一个数组中
                $gidArr[] = $gid;   

            }
            
            // 序列化保存到cookie中
            cookie('recentViews', serialize($gidArr), config('view_cookie_lifetime') );

            return true;

        // }
        

    }

    /**
     * 获取最近浏览商品
     * @param  integer $cid [description]
     * @return [type]       [description]
     */
    public function getRecentviewedGoods( $cid = 0, $num = 5, $strlen = 16 ){

        // 检测用户是否登录，登录就在数据库获取信息，没有就在cookie中获取信息
        // if( session('mid') ){

        //     $gids =[];

        // }else{

            // 检测cookie中是否已经设置过最近浏览数据，设置了就反序列化返回，否则返回一个空数组
            $gids = cookie('recentViews') ? unserialize( cookie('recentViews') ) : [];

        // }

        // 获取商品信息
        $goods = [];
        if( $gids ){
           
            $gids = array_map('intval', array_slice($gids, 0,$num));
            $field = 'goods_name,static_url,shop_price,is_promote,promote_start_time,promote_end_time,promote_price,pic_small';

            // 传递了分类id
            if( $cid+0 ){

                $where = "g.gid in (".implode(',', $gids).") AND (g.cid = {$cid} OR gc.cid = {$cid})";
                $field .= ',g.gid';
                $goods = $this->alias('g')->field( $field )->join("jd_goods_category gc","g.gid = gc.gid","LEFT")->where( $where )->order("FIELD (g.gid,".implode(',', $gids).")")->select()->toArray();

                // echo $this->getLastSql();die;

            }else{

                $where = "gid in (".implode(',', $gids).")";

                $field .= ',gid';
                $goods = $this->field( $field )->where( $where )->order("FIELD (gid,".implode(',', $gids).")")->select()->toArray();

            }

            // 处理商品名称长度
            foreach ($goods as $k => $v) {
                
                if( mb_strlen($v['goods_name'],'utf-8') > $strlen ){

                    $goods[$k]['goods_name'] = mb_substr($v['goods_name'], 0,$strlen,'utf-8').'...';

                }

            }
            
        }
        
        return $goods;

    }
    
    /**
     * 获取手机、数码分类信息
     * @return [type] [description]
     */
    public function getPhoneDigitalInfo(){

        // 储存分类下所有信息
        $category = [];

        // 获取子分类
        $catModel = db('category');
        $data = $catModel->field('cid,parent_id')->select();
        $cids = $this->getSonIds( $data, $pid = 4 );
        $category['sonCats'] = $catModel->field('cid,cat_name')->where('cid','in',$cids)->limit(18)->select();

        // 获取分类下品牌
        $cids[] = 4;
        $bids = $this->where('cid','in',$cids)->column('bid');
        $bids = array_slice( array_unique($bids), 0, 9);
        $category['brands'] = db('brand')->where( ['bid'=>['in',$bids],'brand_status'=>1])->order('sort')->select();

        return $category;
    }



}